package me.younian.transmitNIO;

/**
 * Created by Administrator on 2017/4/1.
 */

import org.apache.log4j.Logger;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HandlerClient extends IoHandlerAdapter {
    private static final Logger logger = Logger.getLogger(HandlerClient.class);

    @Override
    public void sessionOpened(IoSession session) {
        session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 60);
        if (ClientSession.getClientSession() == null) {
            logger.info("Client Connected...");
        } else {
            logger.info("Client Updated...");
        }
        ClientSession.setClientSession(session);
        //session.write("CONNECTED");
    }

    @Override
    public void messageReceived(IoSession session, Object message) {
        // HttpRequestMessage request = (HttpRequestMessage) message;

        HttpResponseMessage response = new HttpResponseMessage();

        response.setResponseCode(HttpResponseMessage.HTTP_STATUS_SUCCESS);

        Map<String, Object> map = (HashMap) message;
        String id = (String) map.get("id");
        Map<String, Object> res = (HashMap) map.get("res");
        response.appendBody((String) res.get("body"));

        Map<String, List<String>> header = (Map<String, List<String>>) res.get("header");

        Map<String, String> be = response.getHeaders();
        for (String key : be.keySet()) {
            System.out.println(key + ":" + be.get(key));
        }

        for (String key : header.keySet()) {
            if (key == null || key.equals("null")) {
                continue;
            }
            if (key.equals("Content-Length")) {
                continue;
            }
            response.setHeaders(key, header.get(key).get(0));
        }

        System.out.println("=============================");
        Map<String, String> af = response.getHeaders();
        for (String key : af.keySet()) {
            System.out.println(key + ":" + af.get(key));
        }

        IoSession requestSession = RequestMap.map.get(id);
        if (requestSession != null) {
            requestSession.write(response);
            requestSession.closeOnFlush();
        }
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status) {
        logger.info("sessionIdle");
    }

    @Override
    public void sessionClosed(IoSession arg0) throws Exception {
        logger.info("sessionClosed");
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) {
        cause.printStackTrace();
    }
}
